package com.education.teacher.shiro;

import com.education.teacher.redis.RedisManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * Created by lzh on 2017/8/15.
 * 共享会话管理器
 *
 * 由Spring-session替代
 */
@Deprecated
public class ShareSessionDao extends AbstractSessionDAO {

    private Logger logger= LogManager.getLogger(ShareSessionDao.class);


    /**
     *  自定义redis key的前缀
     */
    private String keyPrefix;


    /**
     * 自定义的操作方法类
     */
    private RedisManager redisManager;


    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.generateSessionId(session);
        super.assignSessionId(session, sessionId);
        updateSession(session); // 将session存入到redis
        logger.info("sessionId:"+sessionId+"[创建]");
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if(sessionId == null){
            logger.error("doReadSession:sessionId为null");
            return null;
        }
        //TODO 从redis中获取反序列化的session对象
        Session se=redisManager.get(keyPrefix+sessionId);
        logger.info("sessionId:"+sessionId+"[读取]");
        return se;
    }

    @Override
    public void update(Session session){
        updateSession(session); //更新session
    }

    @Override
    public void delete(Session session) {
        if(session == null || session.getId() == null){
            logger.error("session或者sessionId为null");
            return;
        }
        //TODO 移除redis中的session
        logger.info("sessionId:"+session.getId()+"[删除]");
        redisManager.delete(keyPrefix+session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        logger.info("获取所有session");
        return redisManager.getPrefixBy(keyPrefix);
    }


    /**
     * 在redis中创建或者更新session
     * @param session
     */
    private void updateSession(Session session){
        redisManager.set(keyPrefix+session.getId(),session);
    }

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }


    public void setRedisManager(RedisManager redisManager) {
        this.redisManager = redisManager;
    }
}
